//
//  DataRequest.m
//  LeadMagazine
//
//  Created by yuzhou on 13-3-12.
//  Copyright (c) 2013年 fred. All rights reserved.
//

#import "DataRequest.h"
#import "ASIHTTPRequest.h"
#import "ASIDownloadCache.h"

@implementation DataRequest

static DataRequest *dataRequest;

+ (DataRequest *)sharedRequest
{
    if (dataRequest == nil) {
        dataRequest = [[DataRequest alloc] init];
    }
    return dataRequest;
}

- (id)init
{
    self = [super init];
    if (self) {
        [ASIHTTPRequest setDefaultCache:[ASIDownloadCache sharedCache]];
    }
    return self;
}

- (id)getDataFromURLString:(NSString *)URLString cached:(BOOL)cached alert:(BOOL)alert
{
    NSLog(@">>>接口地址>>>%@",URLString);
    NSURL *URL = [NSURL URLWithString:[URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:URL];
    if (cached) {
        request.cachePolicy = ASIFallbackToCacheIfLoadFailsCachePolicy;
        request.cacheStoragePolicy = ASICachePermanentlyCacheStoragePolicy;
        request.secondsToCache = 3*24*60*60;
    }
    [request startSynchronous];
    
    NSError *error = request.error;
    if (error) {
        NSLog(@">>>接口错误>>>%@",error);
    }
    else {
        NSLog(@">>>返回数据>>>%@",request.responseString);
        if (request.responseData == nil) {
            return nil;
        }
        if ([URLString rangeOfString:@"get.article.info"].location != NSNotFound) {
            return request.responseString;
        }
        if ([URLString rangeOfString:@"get.novel.chaptercons"].location != NSNotFound) {
            return request.responseString;
        }
        if ([URLString rangeOfString:@"get.nparticle.info"].location != NSNotFound) {
            return request.responseString;
        }
        if ([URLString rangeOfString:@"get.publicopinion.details"].location != NSNotFound) {
            return request.responseString;
        }

        return [NSJSONSerialization JSONObjectWithData:request.responseData options:NSJSONReadingAllowFragments error:nil];
    }
    return nil;
}

- (id)postDataFromURLString:(NSString *)URLString alert:(BOOL)alert
{
    NSURL *URL = [NSURL URLWithString:[URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:URL];
    [request setRequestMethod:@"POST"];
    [request startSynchronous];
//    NSLog(@">>>接口地址>>>%@",URLString);
    NSError *error = request.error;
    if (error) {
        NSLog(@">>>接口错误>>>%@",error);
    }
    else {
//        NSLog(@">>>返回数据>>>%@",request.responseString);
        if (request.responseData == nil) {
            return nil;
        }
        return [NSJSONSerialization JSONObjectWithData:request.responseData options:NSJSONReadingAllowFragments error:nil];
    }
    return nil;
}

#pragma mark 期刊接口

- (id)getMagazineCategory
{
    NSString *URLString = [NSString stringWithFormat:MagazineCategoryURL];
    return [self getDataFromURLString:URLString cached:YES alert:YES];
}

- (id)getMagazineByCatgory:(NSString *)categoryID
{
    NSString *URLString = [NSString stringWithFormat:MagazineByCategoryURL,categoryID];
    return [self getDataFromURLString:URLString cached:YES alert:YES];
}

- (id)getMagazineInfo:(NSString *)magazineID
{
    NSString *URLString = [NSString stringWithFormat:MagazineInfoURL,magazineID];
    return [self getDataFromURLString:URLString cached:YES alert:YES];
}

- (id)getMagazineContent:(NSString *)magazineID
{
    NSString *URLString = [NSString stringWithFormat:MagazineContentURL,[[AuthorManager defaultManager] userID],magazineID,UUID];
    return [self getDataFromURLString:URLString cached:YES alert:YES];
}

- (id)getArticleInfo:(NSString *)articleID
{
    NSString *URLString = [NSString stringWithFormat:ArticleInfoURL,[[AuthorManager defaultManager] userID],articleID];
    return [self getDataFromURLString:URLString cached:YES alert:YES];
}
- (id)getRecentReadWithItemID:(NSString *)itemID{
    NSString * urlStr = [NSString stringWithFormat:RecentReadUrl,[[AuthorManager defaultManager] userID] ,[[AuthorManager defaultManager] username], itemID];
    return [self getDataFromURLString:urlStr cached:YES alert:YES];
    
}
- (id)getRecentReaded{
    NSString * urlStr = [NSString stringWithFormat:RecentReadedUrl,[[AuthorManager defaultManager] userID] ,[[AuthorManager defaultManager] username]];
    return [self getDataFromURLString:urlStr cached:NO alert:YES];
}
- (id)getSearchInfo:(NSString *)searchStr{
    NSString * urlStr = [NSString stringWithFormat:SearchUrl,searchStr];
    return [self getDataFromURLString:urlStr cached:YES alert:YES];
}
- (id)getHistoryInfo:(NSString *)magazineID{
    NSString * urlStr = [NSString stringWithFormat:HistoryUrl,magazineID];
    return [self getDataFromURLString:urlStr cached:YES alert:YES];
}


#pragma mark 听书接口

- (id)getListenCategory
{
    NSString *URLString = [NSString stringWithFormat:ListenCategoryURL,[[AuthorManager defaultManager] userID]];
    return [self getDataFromURLString:URLString cached:YES alert:YES];
}

- (id)getListenByCatgory:(NSString *)categoryID
{
    NSString *URLString = [NSString stringWithFormat:ListenByCategoryURL,[[AuthorManager defaultManager] userID],categoryID];
    return [self getDataFromURLString:URLString cached:YES alert:YES];
}

- (id)getListenInfo:(NSString *)listenID
{
    NSString *URLString = [NSString stringWithFormat:ListenInfoURL,[[AuthorManager defaultManager] userID],listenID];
    return [self getDataFromURLString:URLString cached:YES alert:YES];
}

- (id)getListenContent:(NSString *)listenID
{
    NSString *URLString = [NSString stringWithFormat:ListenContentURL,[[AuthorManager defaultManager] userID],listenID,UUID];
    return [self getDataFromURLString:URLString cached:YES alert:YES];
}

- (id)getListenComment:(NSString *)listenID
{
    NSString *URLString = [NSString stringWithFormat:ListenCommentURL,[[AuthorManager defaultManager] userID],listenID];
    return [self getDataFromURLString:URLString cached:YES alert:YES];
}
- (id)getListenSearchResult:(NSString *)keyWords{
    NSString * urlStr = [NSString stringWithFormat:SearchListenUrl,[[AuthorManager defaultManager] userID] ,keyWords];
    return [self getDataFromURLString:urlStr cached:YES alert:YES];
}

#pragma mark 小说接口

- (id)getNovelCategory
{
    NSString *URLString = [NSString stringWithFormat:NovelCategoryURL];
    return [self getDataFromURLString:URLString cached:YES alert:YES];
}

- (id)getNovelByCategory:(NSString *)categoryID count:(int)count
{
    NSString *URLString = [NSString stringWithFormat:NovelByCategoryURL,categoryID,count];
    return [self getDataFromURLString:URLString cached:YES alert:YES];
}

- (id)getNovelInfo:(NSString *)novelID
{
    NSString *URLString = [NSString stringWithFormat:NovelInfoURL,novelID, [[AuthorManager defaultManager] userID],UUID];
    return [self getDataFromURLString:URLString cached:YES alert:YES];
}

- (id)getNovelChapterInfo:(NSString *)chapterID
{
    NSString *URLString = [NSString stringWithFormat:NovelChapterInfoURL,chapterID];
    return [self getDataFromURLString:URLString cached:YES alert:YES];
}
- (id)getNovelCollectInfo:(NSString *)novelID{
    NSString * urlStr = [NSString stringWithFormat:NovelCollectURL,novelID, [[AuthorManager defaultManager] userID]];
    return [self getDataFromURLString:urlStr cached:YES alert:YES];
}
- (id)addNovelReadInfo:(NSString *)itemID nc_id:(NSString *)ncID{
    NSString * urlStr = [NSString stringWithFormat:AddNovelReadURL,itemID,ncID,[[AuthorManager defaultManager] userID]];
    return [self getDataFromURLString:urlStr cached:YES alert:YES];
}
- (id)getNovelRecentlyInfo{
    NSString * urlStr = [NSString stringWithFormat:NovelRecentlyReadURL, [[AuthorManager defaultManager] userID]];
    return [self getDataFromURLString:urlStr cached:NO alert:YES];
}
- (id)getNovelSearchResult:(NSString *)keyWords{
    NSString * urlStr = [NSString stringWithFormat:SearchNovlUrl,keyWords];
    return [self getDataFromURLString:urlStr cached:YES alert:YES];
}
#pragma mark 报纸接口

- (id)getRecentNewspaper
{
    NSString *URLString = [NSString stringWithFormat:NewspaperCategoryURL,NEWSPAPERID];
    return [self getDataFromURLString:URLString cached:YES alert:YES];
}
- (id)getHomePage{
    NSString * urlStr = [NSString stringWithFormat:NewspaperHomePageURL,NEWSPAPERID];
    return [self getDataFromURLString:urlStr cached:YES alert:YES];
}
- (id)getNewspaperTextVersions:(NSString *)itemID{
    NSString * urlStr = [NSString stringWithFormat:NewspaperTextVersionURL,itemID];
    return [self getDataFromURLString:urlStr cached:YES alert:YES];
    
}
- (id)getNewspaperPicVersions:(NSString *)itemID imageType:(NSString *)type{
    NSString * urlStr = [NSString stringWithFormat:NewspaperPicVersionURL,itemID,type];
    return [self getDataFromURLString:urlStr cached:YES alert:YES];
}
- (id)getNewspaperPicDes:(NSString *)itemID pageNum:(NSInteger)pageNum{
    NSString * urlStr = [NSString stringWithFormat:NewspaperPicDesURL,itemID ,pageNum];
    return [self getDataFromURLString:urlStr cached:YES alert:YES];
}
- (id)getNewspaperSingleArticle:(NSString *)pageID{
    NSString * urlStr = [NSString stringWithFormat:NewspaperSingleArticleURL,pageID];
    return [self getDataFromURLString:urlStr cached:YES alert:YES];

}
- (id)getNewspaperInfoWithYear:(NSString *)year mouth:(NSString *)mouth day:(NSString *)day{
    NSString * urlStr = [NSString stringWithFormat:NewspaperDateURL,day,mouth,year,NEWSPAPERID];
    return [self getDataFromURLString:urlStr cached:YES alert:YES];
}

#pragma mark 动态接口

- (id)getDynamicsHomepage{
    NSString * urlStr = [NSString stringWithFormat:DynamicsHomepageURL];
    return [self getDataFromURLString:urlStr cached:YES alert:YES];
}

- (id)getDynamicsSingleArticle:(NSString *)public_optione_id{
    NSString * urlStr = [NSString stringWithFormat:DynamicsSingleArticleURL,public_optione_id];
    return [self getDataFromURLString:urlStr cached:YES alert:YES];
}

- (BOOL)checkDynamicsUpdate
{
    NSArray *array;
    id obj = [[DataRequest sharedRequest] getDynamicsHomepage];
    if ([obj isKindOfClass:[NSDictionary class]]) {
        array = [obj objectForKey:@"result"];
        if ([array isKindOfClass:[NSArray class]]) {
            int originSum = [[NSUserDefaults standardUserDefaults] integerForKey:@"public_opinion_id"];
            int idSum = 0;
            for (NSDictionary *dic in array) {
                idSum += [dic[@"public_opinion_id"] intValue];
            }
            if (idSum == originSum) {
                return NO;
            }
            else {
                return YES;
            }
        }
    }
    return NO;
}

#pragma mark 账号接口

- (id)loginWithUsername:(NSString *)username password:(NSString *)password
{
    NSString *URLString = [NSString stringWithFormat:LoginURL,username,password];
    return [self getDataFromURLString:URLString cached:NO alert:YES];
}

- (id)registerWithUsername:(NSString *)username password:(NSString *)password email:(NSString *)email
{
    NSString *URLString = [NSString stringWithFormat:RegisterURL,username,password,email];
    return [self getDataFromURLString:URLString cached:NO alert:YES];
}
- (id)modifyPasswordWithOriginPassword:(NSString *)originPassowrd newPassword:(NSString *)newPassword{
    NSString * urlStr = [NSString stringWithFormat:ModifyURL,[[AuthorManager defaultManager] username],originPassowrd,newPassword];
    return [self getDataFromURLString:urlStr cached:NO alert:YES];
}
- (id)modifyTelNumber:(NSString *)telNumber password:(NSString *)password{
    NSString * usrStr = [NSString stringWithFormat:ModifyTelURL,password,[[AuthorManager defaultManager] userID],telNumber];
    return [self getDataFromURLString:usrStr cached:NO alert:YES];
}

#pragma mark 激活接口
- (id)getActivateInfoUUID:(NSString *)uuid activateNum:(NSString *)activateNum{
    NSString * urlStr = [NSString stringWithFormat:ActivateUserURL,uuid,activateNum];
    return [self getDataFromURLString:urlStr cached:YES alert:YES];
}
- (id)getUUIDInfo:(NSString *)uuid{
    NSString * urlStr = [NSString stringWithFormat:UUIDIsActivatedURL,uuid];
    return [self getDataFromURLString:urlStr cached:YES alert:YES];
}

#pragma mark 程序更新 
//苹果服务器
- (id)detectionUpdate{
    NSString * urlStr = [NSString stringWithFormat:DetectionUpdate,ITUNES_APP_KEY];
    return [self getDataFromURLString:urlStr cached:NO alert:YES];
}
//公司服务器
- (id)getAppVersionInfo{
    NSString * urlStr = [NSString stringWithFormat:GetAppVersionURL,IDENTIFY_KEY,APP_KEY];
    return [self getDataFromURLString:urlStr cached:NO alert:NO];
}


@end
